/**
 * popup.js
 * @fileOverview Contains the javascript code that controls the behavior of the elements in popup.html.
 * @author Matthew George
 * @version 1.3.6
 * 
 * @license Copyright 2009-2010 Matthew George
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// ========================= GLOBAL VARIABLES AND SETTINGS ==============================
// ===Reference variables===
/** @description Reference to the extension's background page.
 * @type {*}
 * @private
 */
var bkpage;

// ===Status variables===
/** @description Stores current status of search box.
 * @type {boolean}
 * @private
 */
var searchBoxHidden;

/** @description Stores the messageBar Timeout object; is empty if messageBar is hidden.
 * @type {?boolean}
 * @private
 */
var messageShown;

// ===Error message settings===
/** @description Message displayed when a url is given that uses a protocol other than http.
 * @const
 * @type {string}
 * @private
 */
var notHttpMessage = "Please enter a valid http address";

/** @description Message displayed when an empty search string is returned by user.
 * @const
 * @type {string}
 * @private
 */
var emptyStringMessage = "Please enter a web address in the search box";

/** @description Length of time that a message is displayed in milliseconds.
 * @const
 * @type {number}
 * @private
 */
var messageTimeout = 15000;

// ============================= INTERNAL FUNCTIONS =====================================
/** @description Sets the search box to the default value.
 *	@private
 */
function resetBoxURL() {
	chrome.tabs.getSelected(undefined, function(tab) {	//get the current tab
		// check if tab url is http protocol;
		// if yes, set search box to current url and set basic search mode
		// if no, set and lock advanced mode and leave search box empty
		if(tab.url.substr(0,7) == "http://") {
			$('#searchurl').val(tab.url.substr(7)); //set box url to current url
			$('#urlInputSection').hide(); //make sure search box is hidden
		}
		else {
			$('#urlInputSection').show(); //show search box
			$('#searchurl').focus(); //set focus to search box
			$('#searchTypeBtn').css('opacity', 0); //hide mode switch button
		}
	});
}

/** @description Displays an alert message.
 *	@param {string} message The message to be displayed.
 *	@private
 */
function displayMessage(message) {
	//make sure a message isn't already being shown	
	if(messageShown == null) { //message bar is hidden
		$('#messageBarText').text(message); //set message text
		
		// show message bar
		$('#messageBar').slideDown("slow", function() {
			// start timer, hide bar at timeout
			messageShown = setTimeout(function() {
				$('#messageBar').slideUp("slow");
				messageShown = null;
			}, messageTimeout);
		});
	}
	else { //message bar is not hidden
		clearTimeout(messageShown); //stop timer
		
		//fade out old message and fade in new message
		$('#messageBar').fadeOut('slow', function() {
			$('#messageBarText').text(message);
			$('#messageBar').fadeIn('slow', function() {
				//restart timer, hide bar at timeout
				messageShown = setTimeout(function() {
					$('#messageBar').slideUp('slow');
					messageShown = null;
				}, messageTimeout);
			});
		});
	}
}

/** @description Gets the input from the search box and returns it if it is a valid http url.
 *	@return {?Array.<string>} An array describing the given url.
 *	@private
 */
function getURL() {
	var txt = $('#searchurl').val(); //get string from textbox
	var url = bkpage.parseUrl(txt); //parse the string
	
	//Check if error was returned
	if(url[0] == -1) {
		//Error returned
		//determine error type and show appropriate message
		switch(url[1]) {
			case 1:
				displayMessage(emptyStringMessage);
				break;
				
			case 2:
				displayMessage(notHttpMessage);
				break;
				
			default:
				displayMessage(notHttpMessage);
		}
		
		//set url as undefined
		url = undefined;
	}
	
	return url;
}

//function loadSearchArchives() {
	//Dragons have begun nesting here.
	//I am not brave enough to fight them off.
//}

// ================================= PAGE EVENT HANDLERS ===========================================
/** @description Submits the search form.
 *	@return {boolean} Always returns false.
 */
function formSubmit() {
	var url = getURL(); //get url string from textbox
	
	// check if null url string was returned;
	// if not null, get selected archive and send
	// a search request to background page
	if(url) {
		bkpage.searchArchive(url, $('#archiveList').val());
	}
	return false;
}

/** @description Toggles whether or not the searchbox is displayed.
 */
function toggleSearchType() {
	// determine whether search box is hidden
	if(searchBoxHidden) {
		// search box is currently hidden;
		// show search box and change button text
		$('#searchTypeBtn').text('Basic Search');
		$('#urlInputSection').slideDown('slow', function() {
			// once slide animation is complete, set focus
			// to search box and record current status
			$('#searchurl').focus();
			searchBoxHidden = false;
		});
	}
	else {
		// search box is currently displayed
		// change button text and hide search box
		$('#searchTypeBtn').text('Advanced Search');
		$('#urlInputSection').slideUp('slow', function() {
			// once slide animation is complete, record
			// current status and reset search box value
			// to current url
			searchBoxHidden = true;
			resetBoxURL();
		});
	}
}

/** @description Opens a new tab to the homepage url.
 */
function openHomepage() {
	// open new tab to homepage
	chrome.tabs.create({url: "http://mgeorge.iblogger.org"});
}

/** @description The page initilization function.
 */
function pageInit() {
	// Get background page from Chrome
	bkpage = chrome.extension.getBackgroundPage();
	
	// Load archives
	// This function would've helped with centralizing the archive info.
	// I'm too lazy to finish it in this version.
	//loadSearchArchives();
	
	// Search box is hidden initially
	searchBoxHidden = true;
	
	// Obtain current page URL, set search box text to URL
	resetBoxURL();
	
	// Setup button event handlers
	$('form').submit(formSubmit);
	$('#searchTypeBtn').click(toggleSearchType);
	$('#homepageLink').click(openHomepage);
}

$(document).ready(pageInit);